package com.neuedu.it.teach.controller.interceptor;

import com.neuedu.it.teach.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器被调用");

        // 获取请求方法
        String method = request.getMethod();
        System.out.println("请求方法: " + method);

        // 处理预检请求 (OPTIONS)
        if ("OPTIONS".equalsIgnoreCase(method)) {
            System.out.println("处理预检请求");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }

        String token = request.getHeader("Authorization");
        System.out.println("token:"+token);
        if (token == null || token.isEmpty()) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\",data:null}");
            System.out.println("here");
            return false;
        }
        System.out.println("token:"+token);
        try {
            Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();

            // 从 claims 中获取用户信息
            Integer userId = (Integer) claims.get("user_id");
            String userNickName = (String) claims.get("user_nickName");
            String username=(String) claims.get("user_name");
            // 根据获取的用户信息构造一个新的 User 对象
            User u = new User();
            u.setId(userId);
            u.setName(username);
            u.setNickName(userNickName);
            // 你可以继续填充其他字段

            System.out.println("解析出来的用户：" + u);
            request.setAttribute("user", u);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"msg\":\"凭证过期或被篡改，请重新登录\",data:null}");
            return false;
        }
    }

}
/*    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\",data:null}");
            return false;
        }
        try {
            Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
            User u = claims.get("user", User.class);
            System.out.println("解析出来的"+u);
            request.setAttribute("user", u);
            return true;
        } catch (Exception e) {
            e.printStackTrace();  // 输出异常栈信息
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"凭证过期或被篡改，请重新登录\",data:null}");
            return false;
        }

    }*/